<template>
  <div id="app">
    <div id="up_div">
      <div class="app-container">
        <divider title="盘库单基本信息"></divider>
        <el-divider></el-divider>
        <el-form ref="form" :model="form"  label-width="80px">
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="盘库单号">
                <el-input v-model="form.inventoryCheckOrderNo" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="6">
              <el-form-item label="仓库" prop="warehouseId">
                <el-select v-model="form.warehouseId" placeholder="请选择仓库" style="width: 65%" disabled>
                  <el-option v-for="item in this.warehouseSelect" :key="item.value" :label="item.label" :value="item.value"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="库区"  prop="warehouseAreaId">
                <el-select v-model="form.warehouseAreaId" placeholder="请选择库区" style="width: 65%" disabled>
                  <el-option v-for="item in this.warehouseAreaSelect" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
                <!--                <el-input v-model="form.warehouseAreaId" :disabled="!form.warehouseId"></el-input>-->
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="货架" prop="warehouseRackId">
                <el-select v-model="form.warehouseRackId" placeholder="请选择货架" style="width: 65%" disabled>
                  <el-option v-for="item in this.warehouseRackSelect" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="货位" prop="warehouseLocationId">
                <el-select v-model="form.warehouseLocationId" placeholder="请选择货位" style="width: 65%" disabled>
                  <el-option v-for="item in this.warehouseLocationSelect" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>

          </el-row>
          <el-row :gutter="24">

            <el-col :span="12">
              <el-form-item label="备注">
                <el-input
                  type="textarea"
                  :rows="2"
                  placeholder="请输入内容"
                  v-model="form.remark">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="3">
              <el-form-item label="盈亏数">
                <el-input v-model="form.totalQuantity" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">

            </el-col>

          </el-row>
        </el-form>
      </div>
    </div>
    <div id="down_div">
      <div class="app-container">
        <divider title="商品明细"></divider>
        <el-divider></el-divider>
        <div class="app-container">
          <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">

            <el-form-item label="商品名称" prop="orderNo">
              <el-input
                v-model="queryParams.productName"
                placeholder="请输入商品名称"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="商品编码" prop="outboundOrderNo">
            <el-input
              v-model="queryParams.productCode"
              placeholder="请输入商品编码"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
            <el-form-item label="入库时间" >
              <el-date-picker
                v-model="dateList"
                type="daterange"
                align="right"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd HH:mm:ss"
                :default-time="['00:00:00', '23:59:59']"
                :picker-options="pickerOptions">
              </el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="localSearch">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
        <el-table
          :data="tableData"
          height="250"
          v-if="show"
          border
          style="width: 100%">
          <!--          <el-table-column
                      prop="id"
                      label="id"
                      width="180">
                    </el-table-column>-->
          <el-table-column
            prop="productName"
            label="商品名称"
            width="180">
          </el-table-column>
          <el-table-column label="商品编码" align="center" prop="productCode" />
          <el-table-column label="规格型号" align="center" prop="productSpec" />
          <el-table-column label="单位" align="center" prop="productUnit" >
            <template slot-scope="scope">
              <dict-tag :options="dict.type.wms_product_unit" :value="scope.row.productUnit">
              </dict-tag>
            </template>
          </el-table-column>
          <el-table-column label="入库时间" align="center" prop="createTime" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>

          <el-table-column label="账面库存" align="center" prop="totalQuantity" />
          <el-table-column label="盈亏数" align="center" prop="difference" />
          <!-- 循环渲染多个可编辑列 -->
          <el-table-column
            v-for="column in editableColumns"
            :key="column.prop"
            :prop="column.prop"
            :label="column.label"
            :width="column.width"
            header-align="center"
          >
            <template #default="{ row, $index }">

              <!-- 当字段是 realTotalQuantity 时使用不带精度的输入框 -->
              <el-input-number
                v-if="column.prop === 'realTotalQuantity'"
                v-model="row[column.prop]"
                :min="1"
                @change="(val) => calculateAmount(row, val)"
                :placeholder="'请输入' + column.label"
              ></el-input-number>
            </template>
          </el-table-column>
        </el-table>
        <el-table
          :data="filteredTableData"
          v-if="filteredShow"
          height="250"
          border
          style="width: 100%">
          <!--          <el-table-column
                      prop="id"
                      label="id"
                      width="180">
                    </el-table-column>-->
          <el-table-column
            prop="productName"
            label="商品名称"
            width="180">
          </el-table-column>
          <el-table-column label="商品编码" align="center" prop="productCode" />
          <el-table-column label="规格型号" align="center" prop="productSpec" />
          <el-table-column label="单位" align="center" prop="productUnit" >
            <template slot-scope="scope">
              <dict-tag :options="dict.type.wms_product_unit" :value="scope.row.productUnit">
              </dict-tag>
            </template>
          </el-table-column>
          <el-table-column label="入库时间" align="center" prop="createTime" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>

          <el-table-column label="账面库存" align="center" prop="totalQuantity" />
          <el-table-column label="盈亏数" align="center" prop="difference" />
          <!-- 循环渲染多个可编辑列 -->
          <el-table-column
            v-for="column in editableColumns"
            :key="column.prop"
            :prop="column.prop"
            :label="column.label"
            :width="column.width"
            header-align="center"
          >
            <template #default="{ row, $index }">

              <!-- 当字段是 realTotalQuantity 时使用不带精度的输入框 -->
              <el-input-number
                v-if="column.prop === 'realTotalQuantity'"
                v-model="row[column.prop]"
                :min="1"
                @change="(val) => calculateAmount(row, val)"
                :placeholder="'请输入' + column.label"
              ></el-input-number>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div id="foot_div">
      <div class="button-group">
        <el-button type="primary" icon="el-icon-plus" @click="handleSubmit">完成盘库</el-button>
        <el-button type="warning" @click="handleSaveTemp">暂存</el-button>
        <el-button @click="handleCancel">取消</el-button>
      </div>
    </div>
  </div>
</template>
<script>
import divider from "@/components/divider"
import {getWarehouseSelect,
  getWarehouseAreaSelect,
  getWarehouseRackSelect,
  getWmsWarehouseLocationSelect} from "@/api/system/selectVo"
import {getInboundProductsByWmsInventoryCheckEdit} from "@/api/system/wmsOutbound";
import {updateWmsInventoryCheck} from "@/api/system/wmsInventoryCheck";

export default {
  name:"AddWmsInventoryCheck",
  props:{
    editFormQueryParam:{}
  },
  dicts:['wms_product_unit'],
  components:{
    divider
  },
  data(){
    return{
      dateList:"",
      filteredShow:false,
      show:true,
      form:{
        inventoryCheckOrderNo:"",
        warehouseId:"",
        warehouseAreaId:"",
        warehouseRackId:"",
        warehouseLocationId:"",
        totalQuantity: 0,
        inventoryCheckStatus: "",
        operationId: "",
        inventoryHistoryList:[],
      },
      warehouseSelect:[],
      warehouseAreaSelect:[],
      warehouseRackSelect:[],
      warehouseLocationSelect:[],
      editableColumns: [
        { prop: 'realTotalQuantity', label: '实际库存', width: '250' },
      ],
      tableData:[],
      filteredTableData :[],
      queryParams: {
        createTime: '',
        productName: '',
        productCode: ''
      },
      // 显示搜索条件
      showSearch: true,
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
    }
  },
  watch:{
  },
  created() {
    this.form = this.editFormQueryParam;

    console.log(this.editFormQueryParam);
    console.log(this.form);
    this.getSelect();
    this.getList();
  },
  methods:{
    getList(){
      getInboundProductsByWmsInventoryCheckEdit(this.form).then( response => {
        this.tableData = response.data.map(item => ({
          ...item,
          realTotalQuantity: item.realTotalQuantity ?? item.totalQuantity, // 如果为空则设为 1
          difference: item.realTotalQuantity - item.totalQuantity, // 同时初始化 difference
        }));
      })
    },
    handleSubmit(){
      this.form.inventoryHistoryList=this.tableData;
      this.form.inventoryCheckStatus = "1";
      this.form.inventoryHistoryList = this.tableData
      updateWmsInventoryCheck(this.form).then(response => {
        this.$message.success('盘库成功');
        this.$emit('handleCancel');
      })
    },
    handleSaveTemp(){
      this.form.inventoryHistoryList=this.tableData;
      this.form.inventoryCheckStatus = "2";
      updateWmsInventoryCheck(this.form).then(response => {
        this.$message.success('盘库成功');
        this.$emit('handleCancel');
      })
    },
    handleCancel(){
      this.$emit("handleCancel");
    },
    getSelect(){
      getWarehouseSelect().then( response =>{
        this.warehouseSelect = response.data
      });
      getWarehouseAreaSelect().then( response =>{
        this.warehouseAreaSelect = response.data
      });
      getWarehouseRackSelect().then( response =>{
        this.warehouseRackSelect = response.data
      });
      getWmsWarehouseLocationSelect().then( response =>{
        this.warehouseLocationSelect = response.data
      });
    },
    parseTime(time, format) {
      if (!time) return '-'
      const date = new Date(time)
      const y = date.getFullYear()
      const m = (date.getMonth() + 1).toString().padStart(2, '0')
      const d = date.getDate().toString().padStart(2, '0')
      const h = date.getHours().toString().padStart(2, '0')
      const i = date.getMinutes().toString().padStart(2, '0')
      const s = date.getSeconds().toString().padStart(2, '0')
      return `${y}-${m}-${d} ${h}:${i}:${s}`
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    //商品明细根据改编数量来改变金额和总金额和总数量
    calculateAmount(row) {
      this.$set(row, 'difference', row.realTotalQuantity - row.totalQuantity);

      this.computedData();

    },
    computedData(){
      let totalQuantity = 0;
      this.tableData.forEach(item => {
        totalQuantity += Number(item.difference) || 0;
      });
      this.form.totalQuantity=totalQuantity;
      // 如果需要强制Vue更新视图（某些特殊情况可能需要）
      this.$forceUpdate();
    },

    localSearch() {
      const { productName, productCode } = this.queryParams;
      const [startTime, endTime] = this.dateList || [null, null]; // 获取日期范围

      this.filteredTableData = this.tableData.filter(item => {
        // 1. 商品名称匹配
        const nameMatch = productName
          ? item.productName?.toLowerCase().includes(productName.toLowerCase()) ?? false
          : true;

        // 2. 商品编码匹配
        const codeMatch = productCode
          ? item.productCode?.toLowerCase().includes(productCode.toLowerCase()) ?? false
          : true;

        // 3. 时间范围匹配（关键改进）
        const timeMatch = startTime && endTime
          ? this.isTimeInRange(item.createTime, startTime, endTime)
          : true;

        return nameMatch && codeMatch && timeMatch;
      });

      this.filteredShow = true;
      this.show = false;
    },

    // 新增方法：判断时间是否在范围内
    isTimeInRange(time, start, end) {
      const itemTime = new Date(time).getTime();
      const startTime = new Date(start).getTime();
      const endTime = new Date(end).getTime();
      return itemTime >= startTime && itemTime <= endTime;
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        productName: '',
        productCode: ''
      };
      this.dateList = []; // 清空日期范围

      this.mergeInventoryData(this.tableData,this.filteredTableData)

      this.filteredShow=false;
      this.show=true;
    },
    /**
     * 智能合并数据（根据inboundId判断是否需要更新realTotalQuantity）
     * @param {Array} sourceData - 原始数据（this.tableData）
     * @param {Array} filteredData - 过滤后的数据（this.filteredTableData）
     * @returns {Array} 合并后的新数据
     */
    mergeInventoryData(sourceData, filteredData) {
      // 创建一个映射以便快速查找
      const sourceMap = new Map();
      sourceData.forEach(item => {
        sourceMap.set(item.inboundId, item);
      });

      // 遍历过滤后的数据，进行智能合并
      return sourceData.map(sourceItem => {
        const filteredItem = filteredData.find(
          item => item.inboundId === sourceItem.inboundId
        );

        // 如果找到匹配项且realTotalQuantity不同，则合并更新
        if (filteredItem && filteredItem.realTotalQuantity !== sourceItem.realTotalQuantity) {
          return {
            ...sourceItem,
            realTotalQuantity: filteredItem.realTotalQuantity,
            difference: filteredItem.realTotalQuantity - sourceItem.totalQuantity
          };
        }
        return sourceItem; // 无变化则返回原数据
      });
    }
  },
}

</script>
<style scoped lang="scss">
body, html {
  margin: 0;
  padding: 0;
  height: 100%;
  overflow: hidden; /* 防止整个页面滚动 */
}

#app {
  background-color: #ffffff;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  padding: 3px;
  display: flex;
  flex-direction: column;
  position: relative;
}

#up_div {
  background-color: white;
  height: 30%;
  width: 100%;
  margin-bottom: 20px;
  box-sizing: border-box;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  border-radius: 4px;
  overflow-y: auto; /* 允许内容滚动 */
}

#down_div {
  background-color: white;
  flex: 1; /* 占据剩余空间 */
  width: 100%;
  box-sizing: border-box;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  border-radius: 4px;
  overflow-y: auto; /* 允许内容滚动 */
  margin-bottom: 60px; /* 为底部按钮留出空间 */
}

#foot_div {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 60px;
  background-color: #fff;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.button-group {
  display: flex;
  gap: 20px;
}

.app-container {
  padding: 20px;
}
</style>
